package lucene.server.cdc.util;

import lucene.server.common.utils.StringUtil;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SqlParser {


    /**
     * 判断数据库是否在filter里面
     * */
    public static boolean isInFilter(String dbName,String[] filters)
    {
        if (StringUtil.isEmpty(dbName)){
            return false;
        }
        if (filters==null || filters.length == 0 || "*".equals(filters[0])){
            return true;
        }
        for (String filterStr : filters){
            if (filterStr.toLowerCase().equals(dbName.toLowerCase())){
                return true;
            }
        }
        return false;
    }
    /**
     * 判断给定的 SQL 语句属于哪种 DDL 类型。
     *
     * @param sql DDL SQL 语句
     * @return DDL 类型
     */
    public static String determineDDLType(String sql) {

        // 匹配 CREATE TABLE 语句
        Pattern patternCreateTable = Pattern.compile("^\\s*CREATE\\s+TABLE", Pattern.CASE_INSENSITIVE);
        Matcher matcherCreateTable = patternCreateTable.matcher(sql);
        if (matcherCreateTable.find()) {
            return "CREATE TABLE";
        }

        // 匹配 ALTER TABLE 语句
        Pattern patternAlterTable = Pattern.compile("^\\s*ALTER\\s+TABLE", Pattern.CASE_INSENSITIVE);
        Matcher matcherAlterTable = patternAlterTable.matcher(sql);
        if (matcherAlterTable.find()) {
            return "ALTER TABLE";
        }

        // 匹配 DROP TABLE 语句
        Pattern patternDropTable = Pattern.compile("^\\s*DROP\\s+TABLE", Pattern.CASE_INSENSITIVE);
        Matcher matcherDropTable = patternDropTable.matcher(sql);
        if (matcherDropTable.find()) {
            return "DROP TABLE";
        }

        // 如果没有匹配到任何 DDL 关键字，则返回 null 或者抛出异常
        return null;
    }
    public static String extractTableName(String sql) {
        String regex = "(?i)(?:\\bFROM\\b\\s+|\\bALTER\\b\\s+TABLE\\s+|\\bCREATE\\b\\s+TABLE\\s+|\\bDROP\\b\\s+TABLE\\s+)(`?)([\\w]+)(`)?(?:\\.(`?)([\\w]+)(`)?)?";
        // 创建Pattern对象
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(sql);
        String tableName = null;
        if (matcher.find()) {
            tableName = matcher.group(5);
            if (tableName == null) {
                tableName  = matcher.group(2);
            }
        }
        return tableName;
    }

}
